const { logInfo, getFileList, parseFile, readFileContent, writeJsonFile, processTemplate, hasChinese } = require("./utils");
const { writeFileSync } = require("node:fs");
const { whitelistDirs, whitelistFiles } = require("./config");

logInfo('开始处理vue文件模板部分，请耐心等待...')

const fileList = getFileList('vue');
logInfo(`共找到 ${fileList.length} 个文件`);
fileList.forEach((file) => {
  const path = file.replaceAll('\\', '/');
  if (whitelistDirs && whitelistDirs.some(dir => path.includes(dir))) {
    return
  }
  if (whitelistFiles && whitelistFiles.includes(path)) {
    return
  }
  if (path.includes(".min.js")) {
    return
  }
  const content = readFileContent(file);
  // 获取文件顶部注释
  let headComment = '';
  if (content.startsWith('<!--')) {
    headComment = content.match(/<!--[\s\S]*?-->/)[0];
  }
  const { descriptor } = parseFile(content, file);
  const { template } = descriptor;
  if (template && template.ast && hasChinese(template.content)) {
    const code = processTemplate(template.content)
    const styles = descriptor.styles.map(({ content, lang, scoped, src }) => {
      const langProp = lang ? `lang=\"${lang}\"` : "";
      const scopedProp = scoped ? `scoped` : "";
      const contentStr = content.startsWith('\n') ? content.slice(1) : content;
      return `<style ${langProp} ${scopedProp}>\n${contentStr}\n</style>`;
    }).join("\n");
    const newContent = [
      headComment,
      descriptor.template ? `<template>${code}</template>` : "",
      descriptor.script ? `<script>${descriptor.script.content}</script>` : "",
      styles,
    ].join("\n");
    writeFileSync(file, newContent);
    logInfo(`已处理并写入: ${file}`);
  }
})